/*
 * Copyright Guoling.com All right reserved. This software is the confidential and proprietary information of
 * Guoling.com ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the license agreement you entered into with Guoling.com.
 */
package com.yunji.framework_template.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

import org.apache.commons.httpclient.HttpException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.yunji.framework_template.biz.cache.CacheService;
import com.yunji.framework_template.biz.service.SitesInfoService;
import com.yunji.framework_template.common.constant.Constant;
import com.yunji.framework_template.common.http.Base64Helper;
import com.yunji.framework_template.common.util.AES;
import com.yunji.framework_template.common.util.CookieUtil;
import com.yunji.framework_template.common.util.GeoUtils;
import com.yunji.framework_template.common.util.IPHelper;
import com.yunji.framework_template.common.util.NumberUtil;
import com.yunji.framework_template.orm.datasource.HandleDataSource;
import com.yunji.framework_template.orm.persistence.model.SitesInfo;
import com.yunji.framework_template.web.controller.old.Counter;

/*
 * 类IndexControler.java的实现描述：TODO 类实现描述
 * @author ddp1j32 2015-6-4 上午10:30:48
 */
@Controller
public class IndexControler {

    private static final Logger logger = Logger.getLogger(IndexControler.class);
    @Value("#{settings['test.config']}")
    private String              testConfig;
    @Value("#{settings['system.domain']}")
    private String              systemDomain;

    @Autowired
    private CacheService        cacheService;

    @Resource
    private SitesInfoService    sitesInfoService;

    @ResponseBody
    @RequestMapping(value = "/login", method = { RequestMethod.POST, RequestMethod.GET })
    public Map<String, Object> login(@NotNull HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put(Constant.RESULT_CODE_KEY, Constant.AppCode.SUC);

        return resultMap;
    }

    /**
     * Home page
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) throws HttpException,
                                                                                         IOException {
        CookieUtil.removeCookie(request, response, Constant.USER_SESSION_UID.toString());
        return new ModelAndView("redirect:/home");
    }

    /**
     * Home page
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) throws HttpException,
                                                                                        IOException {

        logger.info("index is accessed.");
        /** 这个是在Nginx中设置的代理头 **/
        String isAgent = request.getHeader("isAgent");
        logger.info("isAgent:" + isAgent);
        if ("true".equals(isAgent)) {// 确认是否是代理nginx
            String ua = request.getHeader("User-Agent");
            logger.info("ua:" + ua);
            if(ua==null) {
            	Counter.addVisit();
            	return new ModelAndView(new RedirectView("http://m.af1234.com"));
            }
            ua = ua.toLowerCase();
            if (Counter.isForward()) {
            	return new ModelAndView(new RedirectView("http://m.af1234.com")); 
            } else {//不跳转的处理逻辑
            	if (ua.indexOf("opera mini") >= 0) {
                    return new ModelAndView(new RedirectView("http://funny.666bbb.net/f_jokes"));
                } else {
                	if (Counter.isForwardToPop()) {// 控制是否需要跳转到yesgood
                        return new ModelAndView(new RedirectView("http://666bbb.net"));
                    } else {
                        logger.info("current index accessed");
                        return index_now(request, response);
                    }
                }
            }   
        } else {
            logger.info("current index accessed");
            return index_now(request, response);
        }
    }

    /**
     * 现在的主页
     * 
     * @param request
     * @param response
     * @return
     */
    private ModelAndView index_now(HttpServletRequest request, HttpServletResponse response) {

        List<SitesInfo> topSites = new ArrayList<SitesInfo>();
        if (HandleDataSource.getRealCountryCode() != null
            && cacheService.getCountries().indexOf(HandleDataSource.getRealCountryCode()) >= 0) {// 是当前支持的国家
            topSites = cacheService.getCache().getTopSites();
            if (topSites == null || topSites.size() == 0) {
                topSites = sitesInfoService.getSitesInfoFromAllCountries();
            }
        } else {
            logger.info("Current country not support:" + HandleDataSource.getRealCountryCode()
                        + ", now get top sites from all countries.");
            topSites = sitesInfoService.getSitesInfoFromAllCountries();
        }
        ModelAndView view = new ModelAndView("home/index");
        view.getModelMap().addAttribute("home", Constant.CURRENT_PAGE);
        view.getModelMap().addAttribute("topSites", topSites);
        view.getModelMap().addAttribute("topWorldSites", cacheService.getCache().getTopWorldSites());
        view.getModelMap().addAttribute("sitesTypesRelationMap", cacheService.getCache().getSitesTypeRelation());
        view.getModelMap().addAttribute("topSitesTypeCodeList", cacheService.getCache().getTopSitesTypeCode());
        view.getModelMap().addAttribute("subTypesTopSites", cacheService.getCache().getSubTypeTopSites());
        view.getModelMap().addAttribute("indexType", "HiIndia");
        view.getModelMap().addAttribute("systemDomain", systemDomain);
        return view;
    }
    /**
     * Home page，该主页主要是给浏览器使用
     */
    @RequestMapping(value = "/browser", method = RequestMethod.GET)
    public ModelAndView browserIndex(HttpServletRequest request, HttpServletResponse response) throws HttpException,
                                                                                        IOException {
        List<SitesInfo> topSites = new ArrayList<SitesInfo>();
        if (HandleDataSource.getRealCountryCode() != null
            && cacheService.getCountries().indexOf(HandleDataSource.getRealCountryCode()) >= 0) {// 是当前支持的国家
            topSites = cacheService.getCache().getTopSites();
            if (topSites == null || topSites.size() == 0) {
                topSites = sitesInfoService.getSitesInfoFromAllCountries();
            }
        } else {
            logger.info("Current country not support:" + HandleDataSource.getRealCountryCode()
                        + ", now get top sites from all countries.");
            topSites = sitesInfoService.getSitesInfoFromAllCountries();
        }
        ModelAndView view = new ModelAndView("home/browserIndex");
        view.getModelMap().addAttribute("home", Constant.CURRENT_PAGE);
        view.getModelMap().addAttribute("topSites", topSites);
        view.getModelMap().addAttribute("topWorldSites", cacheService.getCache().getTopWorldSites());
        view.getModelMap().addAttribute("sitesTypesRelationMap", cacheService.getCache().getSitesTypeRelation());
        view.getModelMap().addAttribute("topSitesTypeCodeList", cacheService.getCache().getTopSitesTypeCode());
        view.getModelMap().addAttribute("subTypesTopSites", cacheService.getCache().getSubTypeTopSites());
        view.getModelMap().addAttribute("indexType", "HiIndia");
        view.getModelMap().addAttribute("systemDomain", systemDomain);
        return view;
    }

    @RequestMapping(value = "/testJsp", method = RequestMethod.GET)
    public ModelAndView testJsp(HttpServletRequest request, HttpServletResponse response) throws HttpException,
                                                                                          IOException {

        logger.info("index is accessed.");
        ModelAndView view = new ModelAndView("rd");
        view.getModelMap().addAttribute("title", "test");
        view.getModelMap().addAttribute("url", "http://www.baidu.com");
        return view;
    }

    @RequestMapping(value = "/testException", method = RequestMethod.GET)
    public ModelAndView testException(HttpServletRequest request, HttpServletResponse response) {
        throw new RuntimeException("not happy");
    }

    @RequestMapping(value = "/testException2", method = RequestMethod.GET)
    public ModelAndView testException2(HttpServletRequest request, HttpServletResponse response) {
        throw new RuntimeException("not happy 2");
    }

    @RequestMapping(value = "/go/{siteId}", method = RequestMethod.GET)
    public ModelAndView go(@PathVariable("siteId") String siteId, HttpServletRequest request) throws HttpException,
                                                                                              IOException {
        siteId = Base64Helper.decode(siteId);
        siteId = AES.decrypt(siteId);
        String location = request.getParameter("location");
        logger.info("Access siteId is:" + siteId);
        if (!NumberUtil.isNumber(siteId)) {
            logger.warn("The siteId is not number:" + siteId);
            return new ModelAndView("404");
        }
        int siteIdInt = Integer.parseInt(siteId);
        SitesInfo sitesInfo = sitesInfoService.selectByPrimaryKey(siteIdInt);
        if (sitesInfo != null) {
            sitesInfoService.updateVisitsTime(sitesInfo);
        }
        return new ModelAndView(new RedirectView(location));
    }
}
